#include "UvServer.h"
UvServer::UvServer()
{
	m_Server.data = this;

	m_pLoop = new uv_loop_t;
	uv_loop_init(m_pLoop);

	uv_tcp_init(m_pLoop, &m_Server);
}

UvServer::~UvServer()
{
	uv_loop_close(m_pLoop);
}

void UvServer::SetPort(int nPort)
{
	m_nPort = nPort;
}

int UvServer::GetPort() const
{
	return m_nPort;
}

bool UvServer::Start()
{
	sockaddr_in addr;
	uv_ip4_addr("0.0.0.0", m_nPort, &addr);
	int nRet = uv_tcp_bind(&m_Server, (const sockaddr*)&addr, 0);

	nRet = uv_listen((uv_stream_t*)&m_Server, 256, OnConnect);

	uv_thread_t tid;
	nRet = uv_thread_create(&tid, ThreadProc, this);
	if (nRet) {
		return false;
	}

	return true;
}

void UvServer::ThreadProc(void* arg)
{
	return ((UvServer*)arg)->ThreadFunc();
}

void UvServer::ThreadFunc()
{
	uv_run(m_pLoop, UV_RUN_DEFAULT);
}

void UvServer::OnConnect(uv_stream_t* server, int status)
{
	UvServer* pServer = (UvServer*)server->data;
	uv_tcp_t* client = new uv_tcp_t;

	uv_tcp_init(pServer->m_pLoop, client);
	int nRet = uv_accept(server, (uv_stream_t*)client);
		pServer->OnConnect(client);

}

void UvServer::OnClose(uv_handle_t* handle)
{
	delete (uv_tcp_t*)handle;
}
